import { Space, Input, message, List, Button } from "antd";
import { useModel } from "umi";
import { useState } from "react";
import { useRelatedOrganization } from "@share-code/public";

const AddRelateOrganization = ({ reloadData }) => {
    const { remoteData, graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { baseInfo, loginInfo } = useModel("person.info");
    const { organizationUuid, organizationInfo } = useModel("organization.info");
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);

    const { loadAllRelatedOrganizations, createRelatedOrganization } = useRelatedOrganization(graphqlFetch);

    const handleSearchAffiliate = async (value) => {
        if (value) {
            setLoading(true);
            let res = await remoteData({
                object: "public-user-auth-center",
                serviceUrl: loginInfo.authCenterUrl,
                serviceName: "/api/v1/organization/searchFullName",
                params: { fullName: value },
            });
            if (res && Array.isArray(res)) {
                let res1 = await loadAllRelatedOrganizations();
                let affiliates = res1 || [];
                setData(res.filter((item) => [...affiliates.map((aff) => aff.oaUuid), organizationUuid].findIndex((item1) => item1 === item.uuid) === -1));
            }
            setLoading(false);
        } else {
            message.warning("名称不能为空");
        }
    };

    const addAffiliate = async (item) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: item.uuid,
            params: {
                apiPath: "/organization/relatedApply",
                data: {
                    oaUuid: organizationUuid,
                    oaName: organizationInfo.fullName,
                    oaCaus: "搜索添加",
                    oaApid: baseInfo.uuid,
                    oaApna: baseInfo.realName,
                },
            },
        });
        if (res) {
            let variables = {
                oaUuid: item.uuid,
                oaName: item.fullName,
                oaCrti: new Date().getUTCTime(),
                oaIsme: true,
                oaCaus: "搜索添加",
                oaApti: new Date().getUTCTime(),
                oaApid: baseInfo.uuid,
                oaApna: baseInfo.realName,
                oaStat: "申请中",
                oaAust: true,
                oaAuti: new Date().getUTCTime(),
            };
            if (res?.oaStat === "待审核") {
                message.warning((res?.oaCaus ? res.oaCaus + ", " : "") + "申请待审核中");
                variables.oaStat = "申请中";
            }
            if (res?.oaStat === "正常") {
                message.success("申请关联的组织已确认");
                variables.oaStat = "正常";
            }
            res = await createRelatedOrganization(variables);
            if (res) {
                message.success("关联组织申请成功");
                reloadData();
                onCloseGlobalModal();
            }
        }
    };

    return (
        <Space direction="vertical" size={20} style={{ width: "100%" }}>
            <Input.Search placeholder="请输入组织名称" onSearch={handleSearchAffiliate} allowClear enterButton />

            <List
                loading={loading}
                header={"组织列表"}
                size="small"
                bordered
                dataSource={data}
                renderItem={(item) => (
                    <List.Item
                        actions={[
                            <Button type="link" onClick={() => addAffiliate(item)}>
                                添加
                            </Button>,
                        ]}
                    >
                        {item.fullName}
                    </List.Item>
                )}
            />
        </Space>
    );
};

export default AddRelateOrganization;
